import 'package:flutter/material.dart';
import 'package:validate/validate.dart';

void main() => runApp(MaterialApp(
  title: "Forms in Flutter",
  home: LoginPage(),
));

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _LoginPageState();
  }
}

class _LoginData {
  String email = '';
  String password = '';
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  _LoginData _data = _LoginData();

  String _validateEmail(String value) {
    // if (!Validate.isEmail(value)) {
    //   return 'The Email Address must be a valid email adress.';
    // } else {
    //   return null;
    // }
    try {
      Validate.isEmail(value);
    } catch (e) {
        return 'The Email Address must be a valid email adress.'; 
    }
    return null;
  }

  String _validatePassword(String value) {
    if (value.length < 8) {
      return 'The password must be at least 8 characters.';
    } else {
      return null;
    }
  }

  void submit() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();

      print('Email: ${_data.email} ,\n Password: ${_data.password}');
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    final screenWidth = MediaQuery.of(context).size.width;
    
    return Scaffold(
      appBar: AppBar(
        title: Text("Login"),
      ),
      body: Container(
        padding: const EdgeInsets.all(20.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: <Widget>[
              TextFormField(
                autofocus: true,
                keyboardType: TextInputType.emailAddress,
                decoration:  InputDecoration(
                  hintText: 'you email',
                  labelText: 'email address'
                ),
                validator: _validateEmail,
                onSaved: (String value) {
                  _data.email = value;
                },
              ),
              TextFormField(
                obscureText: true,
                decoration: InputDecoration(
                  hintText: 'Password',
                  labelText: 'Enter your password'
                ),
                validator: _validatePassword,
                onSaved: (String value) {
                  _data.password = value;
                },
              ),
              Container(
                width: screenWidth,
                child: RaisedButton(
                  child: Text(
                    'Login',
                    style: TextStyle(
                      color: Colors.white
                    ),
                  ),
                  onPressed: submit,
                  color: Colors.blue,
                ),
                margin: EdgeInsets.only(top: 20.0),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
